import random
from math import sin, cos, pi
from tkinter import *

# 画布的宽度和高度
CANVAS_WIDTH = 840
CANVAS_HEIGHT = 680

# 画布中心坐标
CANVAS_CENTER_X = CANVAS_WIDTH // 2  # 画布中心的X坐标
CANVAS_CENTER_Y = CANVAS_HEIGHT // 2  # 画布中心的Y坐标

# 图片放大比例
IMAGE_ENLARGE = 11

# 心形的颜色
HEART_COLOR = "#EEAEEE"

# 居中窗口
def center_window(root, width, height):
    screenwidth = root.winfo_screenwidth()  # 获取屏幕宽度
    screenheight = root.winfo_screenheight()  # 获取屏幕高度
    # 计算窗口的尺寸和位置
    size = '%dx%d+%d+%d' % (width, height, (screenwidth - width)/2, (screenheight - height)/2)
    root.geometry(size)  # 设置窗口尺寸和位置

# 心形函数，计算心形的坐标点
def heart_function(t, shrink_ratio: float = IMAGE_ENLARGE):
    # 参数方程计算心形的X坐标
    x = 17 * (sin(t) ** 3)
    # 参数方程计算心形的Y坐标
    y = -(16 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(4 * t))
    x *= shrink_ratio  # 缩放X坐标
    y *= shrink_ratio  # 缩放Y坐标
    x += CANVAS_CENTER_X  # 平移X坐标到画布中心
    y += CANVAS_CENTER_Y  # 平移Y坐标到画布中心
    return int(x), int(y)  # 返回整数形式的坐标

# 在画布上绘制心形
def draw_heart(canvas):
    points = []  # 存储心形的坐标点
    # 生成心形的所有坐标点
    for t in range(0, 360):
        x, y = heart_function(t * pi / 180)
        points.append((x, y))

    # 通过连接点来绘制心形
    for i in range(len(points) - 1):
        canvas.create_line(points[i], points[i + 1], fill=HEART_COLOR, width=2)
    
    # 闭合心形
    canvas.create_line(points[-1], points[0], fill=HEART_COLOR, width=2)

# 运行应用程序
if __name__ == '__main__':
    root = Tk()  # 创建主窗口
    canvas = Canvas(root, bg="white", height=CANVAS_HEIGHT, width=CANVAS_WIDTH)  # 创建画布
    canvas.pack()  # 将画布放置在主窗口中
    center_window(root, CANVAS_WIDTH, CANVAS_HEIGHT)  # 使窗口居中显示

    draw_heart(canvas)  # 绘制心形

    root.mainloop()  # 进入Tkinter事件循环
